﻿using Microsoft.EntityFrameworkCore;
using star_questionnair.Models;
using star_questionnair.Utilities;

namespace star_questionnair.Services.impl;

public class AnswerService : IAnswerService
{
    private readonly ApplicationDbContext _context;

    public AnswerService(ApplicationDbContext context)
    {
        _context = context;
    }

    public void AddAnswer(Answer answer)
    {
        _context.Answers.Add(answer);
        _context.SaveChanges();
    }

    public void DeleteAnswerById(int id)
    {
        var answer = _context.Answers.Find(id);
        if (answer != null)
        {
            _context.Answers.Remove(answer);
            _context.SaveChanges();
        }
    }

    public void DeleteAnswersByIds(List<int> ids)
    {
        var answers = _context.Answers.Where(a => ids.Contains(a.Id)).ToList();
        _context.Answers.RemoveRange(answers);
        _context.SaveChanges();
    }

    public void UpdateAnswer(Answer answer)
    {
        _context.Answers.Update(answer);
        _context.SaveChanges();
    }

    public Answer GetAnswerById(int id)
    {
        return _context.Answers.Find(id);
    }

    public List<Answer> GetAllAnswers(Answer filter)
    {
        return _context.Answers
            .Where(a =>
                (filter.ResponseId == null || a.ResponseId == filter.ResponseId) &&
                (filter.QuestionId == null || a.QuestionId == filter.QuestionId) &&
                (filter.Content == null || a.Content == filter.Content))
            .ToList();
    }

    public List<Answer> GetAnswersByQuestionId(int questionId)
    {
        return _context.Answers.Where(a => a.QuestionId == questionId).ToList();
    }

    public List<Answer> GetAnswersByOptionId(int optionId)
    {
        return _context.Answers.Where(a => a.Content == optionId.ToString()).ToList();
    }

    public User GetUserByAnswer(Answer answer)
    {
        var response = GetResponseByAnswer(answer);
        return _context.Users.Find(response.UserId);
    }

    public Response GetResponseByAnswer(Answer answer)
    {
        return _context.Responses.Find(answer.ResponseId);
    }

    // 根据 responseId 和 questionId 查询所有相关的答案
    public async Task<List<Answer>> GetAnswerByResponseAndQuestionAsync(int responseId, int questionId)
    {
        // 使用 LINQ 查询获取符合条件的所有答案
        var answers = await _context.Answers
            .Where(a => a.ResponseId == responseId && a.QuestionId == questionId)
            .ToListAsync();
        return answers;
    }
}